﻿namespace MicroCloud.Identity.Database
{
    /// <summary>
    /// 组织机构数据实体映射配置
    /// </summary>

    public class OrganizationConfiguration : EntityTypeConfigurationBase<Organization, long>
    {
        /// <summary>
        /// 重写以实现实体类型各个属性的数据库配置
        /// </summary>
        /// <param name="builder">实体类型创建器</param>
        public override void Configuration(EntityTypeBuilder<Organization> builder)
        {
            //builder.HasIndex(m => new { m.Name, m.ParentId, m.DeletedTime }).HasDatabaseName("IDX_Organization_Name").IsUnique().HasFilter(null);
            //builder.HasIndex(m => new { m.ParentId }).HasDatabaseName("IX_Organization_ParentId").IsUnique(false);
            builder.HasIndex(m => new { m.Code, m.DeletedTime }).SetIndex("Code", true).HasFilter(null);
            builder.HasIndex(m => new { m.Name, m.ParentId, m.DeletedTime }).SetIndex("Name", true).HasFilter(null);
            builder.HasIndex(m => m.ParentId).SetIndex("ParentId", false);
            switch (DbContextOptions?.DatabaseType)
            {
                case DatabaseType.SqlServer:
                case DatabaseType.PostgreSql:
                case DatabaseType.Oracle:
                    //builder.HasIndex(m => new { m.NormalizedName, m.ParentId, m.DeletedTime }).HasDatabaseName("IDX_Organization_NormalizedName").IsUnique().HasFilter(null);
                    //builder.HasIndex(m => new { m.TreePathString }).HasDatabaseName("IDX_Organization_TreePathString").IsUnique();
                    builder.HasIndex(m => new { m.NormalizedName, m.ParentId, m.DeletedTime }).SetIndex("NormalizedName", true).HasFilter(null);
                    builder.HasIndex(m => m.TreePathString).SetIndex("TreePathString", true);
                    break;
            }

            //builder.HasOne(m => m.Parent).WithMany(m => m.Children).HasForeignKey(m => m.ParentId).HasConstraintName("FK_Organization_ParentId").IsRequired(false);
            builder.HasOne(m => m.Parent).WithMany(m => m.Children).HasForeignKey(m => m.ParentId).SetForeignKey("ParentId", false);

            ConfigurationAppend(builder);
        }

    }
}
